package com.buddy.learn.spring.framework.aop.aspect;

import java.lang.reflect.Method;

public abstract class BAbstractAspectAdvice implements BAdvice{
    private Method aspectMethod;
    private Object aspectTarget;

    /**
     * @param aspectMethod 切面方法
     * @param aspectTarget
     */
    public BAbstractAspectAdvice(Method aspectMethod, Object aspectTarget) {
        this.aspectMethod = aspectMethod;
        this.aspectTarget = aspectTarget;
    }

    public Object invokeAdviceMethod(BJoinPoint joinPoint, Object returnValue, Throwable tr) throws Throwable {

        Class<?>[] parameterTypes = this.aspectMethod.getParameterTypes();
        if (null == parameterTypes || parameterTypes.length == 0) {
            return this.aspectMethod.invoke(aspectTarget);
        } else {
            Object[] args = new Object[parameterTypes.length];
            for (int i = 0; i < parameterTypes.length; i++) {
                if (parameterTypes[i] == BJoinPoint.class) {
                    args[i] = joinPoint;
                } else if (parameterTypes[i] == Throwable.class) {
                    args[i] = tr;
                } else if (parameterTypes[i] == Object.class) {
                    args[i] = returnValue;
                }
            }
            return this.aspectMethod.invoke(aspectTarget, args);
        }
    }

}
